<?php

namespace app\api\controller;

use app\admin\model\user\UserMember;
use app\api\logic\SmsLogic;
use app\basic\ApiController;
use hg\apidoc\annotation as Apidoc;
use support\Response;

/**
 * @Apidoc\Title("短信配置")
 */
class SmsController extends ApiController
{

     protected $noNeedLogin = ['*'];

    /**
     * 构造方法
     */
    public function __Construct()
    {
        parent::__construct();
        // 存储配置信息
        $this->logic = new SmsLogic();
    }

    /**
     * @Apidoc\Title("发送短信")
     * @Apidoc\Param ("phone", type="string", require=true, desc="手机号")
     * @Apidoc\Param("type", type="string", require=true, desc="事件名称 如:mobilelogin,register,changemobile,resetpwd,changepwd")
     * @Apidoc\Method("POST")
     */
    public function sendSms(): Response
    {
        return $this->success($this->logic->smsBase());
    }


    /**
     * @Apidoc\Title("检测验证码")
     * @Apidoc\Param ("phone", type="string", require=true, desc="手机号")
     * @Apidoc\Param("type", type="string", require=true, desc="短信类型")
     * @Apidoc\Param("code", type="string", require=true, desc="验证码")
     * @Apidoc\Method("POST")
     */
    public function check()
    {
        $mobile  = $this->request->post("phone");
        $event   = $this->request->post("type");
        $event   = $event ? $event : 'register';
        $captcha = $this->request->post("code");
        $validate = new \think\Validate();
        if (!$mobile || !$validate->regex($mobile, "^1\d{10}$")) {
            return $this->fail('手机号不正确');
        }
        if ($event) {
            $userinfo = UserMember::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                return $this->fail('已被注册');
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                return $this->fail('已被占用');
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                return $this->fail('未注册');
            }
        }
        $ret = SmsLogic::check($mobile, $captcha, $event);
        if ($ret) {
            return $this->success('成功');
        } else {
            return $this->fail('验证码不正确');
        }
    }

}